const path = require('path');

const webpack = require("webpack");

const HtmlWebpackPlugin = require('html-webpack-plugin');

const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

const TerserPlugin = require("terser-webpack-plugin");

const ESLintPlugin = require('eslint-webpack-plugin');

const lessModuleRegex = /\.module\.less$/;
const lessRegex = /\.(less|css)$/;

const isProd = process.env.NODE_ENV == 'production';

const {
    name
} = require('./package');

let babelPlugin = ['react-refresh/babel'];



if (isProd) {
    babelPlugin = [];
}

let plugins = [

    new webpack.DefinePlugin({
        'process.env.aabcd': JSON.stringify(process.env.NODE_ENV),
        'process.env.test': '"我是webpacktest"',
    }),

    // new ESLintPlugin({
    //     exclude:["node_modules"],
    //     extensions:["ts","js","tsx"]
    // }),

    new MiniCssExtractPlugin({
        filename: 'css/[name].css'
    }),

    new ForkTsCheckerWebpackPlugin(),

    new HtmlWebpackPlugin({
        publicPath: isProd ? "./" : "/",
        template: './index.html',
        inject: 'body',
    }),
]

if (!isProd) {
    plugins.push(new ReactRefreshWebpackPlugin());
}

var webpackConfig = {

    target: "browserslist",

    mode: !isProd ? 'development' : "production",

    devtool: !isProd ? "eval-source-map" : false,

    entry: {
        index: './src/index.tsx',
    },

    output: {
        clean: true,
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        chunkFilename: '[name].chunk.js',
        library: `${name}-[name]`,
        libraryTarget: 'umd', // 把微应用打包成 umd 库格式
        chunkLoadingGlobal: `webpackJsonp_${name}`
    },


    devServer: {
        historyApiFallback: true,
        hot: true,
        port: 8098
    },

    module: {

        rules: [{
                test: /\.(js|jsx)$/,
                exclude: /node_modules\/(?!@pmmmwh\/react-refresh-webpack-plugin)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        plugins: babelPlugin
                    },
                }
            },

            {
                test: /\.(ts|tsx)$/,
                exclude: /node_modules\/(?!@pmmmwh\/react-refresh-webpack-plugin)/,
                use: [{
                    loader: 'babel-loader',
                    options: {
                        plugins: babelPlugin
                    },
                }, {
                    loader: 'ts-loader'
                }],
            },

            {
                test: lessRegex,
                exclude: lessModuleRegex,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
            },

            {
                test: lessModuleRegex,
                use: [MiniCssExtractPlugin.loader, {
                    loader: 'css-loader',
                }, {
                    loader: 'less-loader',
                    options: {
                        lessOptions: {
                            modules: true,
                        }
                    }
                }]
            },

            {
                test: /\.(png|jpg|gif|svg)$/,
                loader: 'url-loader',
                options: {
                    name: 'imgs/[name].[hash:4].[ext]',
                    limit: 100,
                    publicPath: '../'
                }
            },

            {
                test: /\.(woff|eot|ttf|otf|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 1,
                    name: 'css/fonts/[name].[hash:4].[ext]',
                    publicPath: '../'
                }
            }

        ]
    },

    plugins,

    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src'),
        },
        extensions: ['.tsx', '.ts', '.js', '.jsx', '.json'],
    },

    resolveLoader: {
        modules: ['node_modules'], // , "myModules"
        // 入口文件的后缀
        extensions: ['.js', '.json'],
    },

    optimization: {
        splitChunks: {
            cacheGroups: {

                common: {
                    name: `chunk-common`,
                    minChunks: 2,
                    priority: -20,
                    chunks: 'initial',
                    reuseExistingChunk: true
                },
                styles: {
                    name: "app",
                    test: /\.css$/,
                    chunks: 'all',
                    enforce: true,
                },
                vendors: {
                    name: 'chunk-vendors',
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10,
                    chunks: 'initial',
                },
                // fix: {
                //   name: 'chunk-fix',
                //   minSize:1,
                //   maxSize:1000000,
                //   test: /fix/,
                //   priority: 10,
                //   chunks: 'initial'
                // },

            },
        },
        minimizer: [
            new TerserPlugin(),
            new CssMinimizerPlugin(),
        ],
    }

}


module.exports = webpackConfig;